<template>
  <el-button
      type="success" icon="el-icon-download" class="ele-btn-icon"
      @click="exportExcel({})" :disabled="disabled" :loading="loading">
    {{loading ? '正在导出...' : buttonName}}
  </el-button>
</template>

<script>
  import { eleTableExportExcel } from '@/utils/excel'

  export default {
    name: 'eleTableExportExcelButton',
    props: {
      // 表格列定义
      columns: {
        type: Array,
        default: () => {
          return []
        }
      },
      // 请求条件
      query: {
        type: Object,
        default: () => {
          return {}
        }
      },
      // 请求地址
      url: {
        type: String,
        default: ''
      },
      // 导出excel名
      excelName: {
        type: String,
        default: 'export-sheet'
      },
      buttonName: {
        type: String,
        default: '批量导出'
      },
      config: {
        type: Object,
        default: () => {
          return {}
        }
      },
      initExport: {
        type: Boolean,
        default: false
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        // 处理状态
        loading: false
      }
    },
    methods: {
      exportExcel (query = {}, load = false) {
        if (this.initExport || load) {
          this.loading = true
          let where = Object.assign(this.query, query)
          eleTableExportExcel(this.columns, where, this.url, this.excelName, this.config).then(() => {
            this.loading = false
          })
        } else {
          this.$emit('click')
        }
      },
      export (query) {
        this.exportExcel(query, true)
      },
      download (where = false) {
        this.loading = true
        this.$http.get(this.url, { params: where, responseType: 'blob' }).then(res => {
          this.loading = false
          let headerContent = res.headers['download-info'] ?? false
          if (headerContent) {
            let info = JSON.parse(res.headers['download-info'])
            let blob = new Blob([res.data], { type: res.headers[''] })
            let url = window.URL.createObjectURL(blob)
            let a = document.createElement('a')
            a.href = url
            a.download = info.name || 'download.xlsx'
            a.click()
            window.URL.revokeObjectURL(url)
          }
        }).catch(() => {
          this.loading = false
        })
      }
    }
  }
</script>

<style scoped>

</style>
